import { httpUpload } from "@/utils/request.js";
import {
  getUserInfo,
  getMajorDetail,
  getLabel,
  getActivityLabel,
  addQuizSubmit,
  getCouponList
} from "@/static/js/quiz.js";
import { appJumpWx } from "@/utils/utils.js";
import {
  completeTask
} from '../../static/js/points.js';
export default {
  data() {
    return {
      userInfo: {}, //用户信息
      userInfo1: {}, //只用于按钮判断
      askContent: "", //问题内容
      imgList: [], //图片列表
      tagsList: [], //标签列表
      subTrue: true, //发布按钮是否可点击
      showPay: false, //支付弹窗
      couponList: [], //优惠券列表
      wenda_money: "", //最终支付的积分
      couponSelected: null, //优惠券对象
      btnAble: false, //支付按钮是否可点击
      showTags: false, //标签弹窗
      tagsSelectedList: [], //标签列表
      activityLabel: [], //活动标签
      showMajorInfo: false, //是否显示老师信息
      majorInfo: {
        user_info: {},
      }, //老师信息
      activityLabelSelectedStr: "", //活动标签字符串
      ans_uid: "", //指定专业人士回答
      showFollow: false, //是否显示关注公众号
      couponNum: 0, //优惠券数量
      pointsObj: {}, //积分对象
    };
  },
  methods: {
    //获取用户信息
    getUserInformation() {
      getUserInfo({}).then((res) => {
        if (res.code == 1) {
          this.userInfo = res.data;
        }
        this.getCouponLists();
        this.init();
      });
    },

    //获取专业提问老师的详情
    getMajorDetail(id) {
      getMajorDetail({
        id: id,
      }).then((res) => {
        if (res.code == 1) {
          this.majorInfo = res.data;
        } else {
          this.$tools.msg(res.msg);
        }
      });
    },

    //点击上传
    uploadClick() {
      uni.chooseImage({
        count: 9, //默认9
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"], //从相册选择
        success: (res) => {
          if (res.tempFilePaths.length > 0) {
            for (let i = 0; i < res.tempFilePaths.length; i++) {
              this.toUpload(res.tempFilePaths[i]);
              uni.showLoading({
                title: "加载中",
              });
            }
          }
        },
      });
    },

    //上传图片
    toUpload(img) {
      httpUpload({
        url: '/api/common/upload',
        method: 'POST',
        params: img
      })
        .then((res) => {
          let res1 = JSON.parse(res)
          if (res1.code == 1) {
            this.imgList.push(res1.data.fullurl);
            uni.hideLoading();
          } else {
            this.$tools.showToast(res1.msg);
          }
        })
        .catch((err) => {
          console.log("错误回调", err);
        });
    },

    //删除图片
    deleteImg(index) {
      let that = this;
      uni.showModal({
        title: "",
        content: "确认删除此图片吗",
        success: function (res) {
          if (res.confirm) {
            that.imgList.splice(index, 1);
          }
        },
      });
    },

    //查看
    previewImage(val) {
      uni.previewImage({
        urls: [val],
      });
    },

    //获取标签列表
    getLabelList() {
      getLabel({}).then((res) => {
        if (res.code == 1) {
          for (let item of res.data) {
            item.checked = false;
          }
          this.tagsList.push(...res.data);
        }
      });
    },

    //获取提问活动标签列表
    getActivityLabel() {
      getActivityLabel().then((res) => {
        if (res.code == 1) {
          for (let item of res.data) {
            item.checked = false;
          }
          this.activityLabel.push(...res.data);
        }
      });
    },

    // 选择标签
    selectedTag(item) {
      let isAdd = !item.checked; //是否是添加操作
      if (this.tagsSelectedList.length >= 3 && isAdd) {
        this.$tools.msg("最多只能选择三个标签");
        return;
      }
      item.checked = !item.checked;
      if (isAdd) {
        this.tagsSelectedList.push(item.name);
      } else {
        let index = this.tagsSelectedList.indexOf(item.name);
        this.tagsSelectedList.splice(index, 1);
      }
    },

    //选择活动标签
    activitySelectTag(item) {
      let isAdd = !item.checked; //是否是添加操作
      item.checked = !item.checked;
      if (isAdd) {
        this.activityLabelSelectedStr = item.name;
      }
    },

    //判断提问是否有内容
    quickSubmit() {
      if (this.askContent.length < 10) {
        this.$tools.msg('请您详细描述您的问题，不得低于10个字。')
        return
      }
      if (this.userInfo.is_wenda_vip > 0 && !this.showMajorInfo) {
				this.submitQuiz()
			} else {
				this.showPay = true
			}
    },

    //发布问题
    submitQuiz() {
      if (this.btnAble) return;
      let that = this;
      let label_id = [];
      for (let item of this.tagsList) {
        if (item.checked) label_id.push(item.id);
      }
      let str = "";
      if (this.activityLabelSelectedStr) {
        str = "#" + this.activityLabelSelectedStr + "#";
      }
      let params = {
        title: str + this.askContent,
        info_images: this.imgList,
        label_id: label_id.join(","),
        ans_uid: this.ans_uid,
        type: 0,
      };

      //有优惠券
      if (this.couponSelected != null) {
        this.$set(params, "coupon_id", this.couponSelected.id);
      }
      //当前是对专家提问
      if (this.showMajorInfo) {
        this.$set(params, "this.ans_uid", this.ans_uid);
      }
      this.btnAble = true;
      addQuizSubmit(params).then((res) => {
        if (res.code == 1) {
          completeTask({
            code: 'A4'
          }).then(res1 => {
            if (res1.code == 1) {
              if (res1.data != null) {
                that.pointsObj = res1.data;
                uni.redirectTo({
                  url: `../chatRoom/index?id=${res.data}&str=${that.activityLabelSelectedStr}&showPointsTips=true&pointsTipsTitle=${that.pointsObj.name}&points=${that.pointsObj.amount}`
                })
              }
            } else if (res1.code == 0) {
              uni.redirectTo({
                url: `../chatRoom/index?id=${res.data}&str=${that.activityLabelSelectedStr}`
              })
            }
          })
        } else {
          setTimeout(() => {
            this.btnAble = false;
          }, 800);
          this.$tools.msg(res.msg);
        }
      });
    },

    //获取优惠券列表
    getCouponLists() {
      let type = 0;
      if (this.showMajorInfo) {
        //专家
        type = 2;
      } else {
        //普通
        type = 1;
      }
      getCouponList({
        status: 0,
        type,
      }).then((res) => {
        if (res.code == 1) {
          this.couponList = res.data.list;
          this.couponNum = res.data.list.length
        } else {
          this.$tools.msg(res.msg);
        }
      });
    },

    //去选择优惠券
    goChooseCoupons() {
      let type = 0;
      let couponId = -1;
      if (this.showMajorInfo) {
        //专家
        type = 2;
      } else {
        //普通
        type = 1;
      }
      if (this.couponSelected) {
        couponId = this.couponSelected.id;
      }

      uni.navigateTo({
        url: "./chooseCoupons?type=" + type + "&couponId=" + couponId,
      });
    },

    //初始化
    init() {
      let m = this.userInfo.wenda_amount;
      if (this.showMajorInfo) {
        m = this.majorInfo.major_cost;
      }
      this.wenda_money = m;
    },

    //去充值
    goPayMoney() {
      uni.navigateTo({
        url: "/pointsMall/recharge/index",
      });
    },

    //跳转到微信小程序扫码关注公众号页面
    toAppJumpWx() {
      appJumpWx('gh_54c7ed1b5bfc')
    },
  },
  onLoad(e) {
    if (e.id) {
      this.ans_uid = e.id;
      this.showMajorInfo = true;
      this.getMajorDetail(e.id);
    }
    this.userInfo1 = uni.getStorageSync('userInfo')
    this.showFollow = this.userInfo1.official_openid == null ? true : false
    this.getLabelList();
    this.getActivityLabel();
    this.getUserInformation();
  },
  onShow() {
    let that = this;
    uni.$on("returnData", function (data) {
      that.couponSelected = data;
    });
  },

  watch: {
    askContent(e) {
      this.subTrue = e == "";
    },

    couponSelected(newVal, oldVal) {
      //先算出原价
      let m = this.userInfo.wenda_amount;
      if (this.showMajorInfo) {
        m = this.majorInfo.major_cost;
      }

      if (newVal != null) {
        if (newVal.num_text == 0) {
          //免单
          this.wenda_money = 0;
        } else {
          this.wenda_money = (m * newVal.num_text) / 10;
        }
      } else {
        this.wenda_money = m;
      }
    },
  },
};